#include<windows.h>
#include<iostream>

using namespace std;

void RemoteFunction(DWORD_PTR param){
	cout << "In remote thread,parameter: " << *reinterpret_cast<long*>(param) << endl;
}

int main(){
	
	HANDLE hMap = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,1024,NULL);
	if(hMap == NULL){
		
		cerr << "CreateFileMapping failed. Error: "<< GetLastError() << endl;
		
		return 1;
		
		
	}
	
	
	LPVOID pView = MapViewOfFile(hMap,FILE_MAP_WRITE,0,0,1024);
	if(pView == NULL){
		cerr << "MapViewOfFile failed. Error: " << GetLastError() << endl;
		CloseHandle(hMap);
		return 1;
	}
	
	DWORD_PTR data = 55;
	memcpy(pView,&data,sizeof(DWORD_PTR));
	
	cout << "DWORD_PTR => " << typeid(DWORD_PTR).name()  << ",bytes: " << sizeof(DWORD_PTR) << endl;
	cout << "pView data: " << *(DWORD_PTR*)pView << endl;
	
	//DWORD targetProcessId = 1460;
	DWORD targetProcessId = GetCurrentProcessId();
	cout << "DWORD => " << typeid(DWORD).name() << ",bytes: " << sizeof(DWORD) << endl;
	cout << "current process id: " << targetProcessId << endl;
	HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,targetProcessId);
	
	if(hProcess == NULL){
		cerr << "OpenProcess failed. Error: " << GetLastError() << endl;
		UnmapViewOfFile(pView);
		CloseHandle(hMap);
		return 1;
	}
	
	DWORD_PTR threadId;
	
	HANDLE hRemoteThread = CreateRemoteThread(hProcess,
							NULL,
							0,
							(LPTHREAD_START_ROUTINE)RemoteFunction,
							pView,
							0,
							reinterpret_cast<LPDWORD>(&threadId));
	
	if(hRemoteThread == NULL){
		cerr << "CreateRemoteThread failed. Error: " << GetLastError() << endl;
	}
	
	WaitForSingleObject(hRemoteThread,INFINITE);
	
	DWORD_PTR readData;
	//BOOL result = ReadProcessMemory(hProcess,
		//							pView,
			//						&readData,
				//					sizeof(DWORD_PTR),
					//				NULL);
									
	BOOL result = ReadProcessMemory(hProcess,
									pView,
									&readData,
									sizeof(DWORD_PTR),
									NULL);
									
									
	if(!result){
		cerr << "ReadProcessMemory failed. Error: " << GetLastError() << endl; 
	}
	
	UnmapViewOfFile(pView);
	CloseHandle(hMap);
	CloseHandle(hProcess);
	CloseHandle(hRemoteThread);
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	return 0;
}


